package com.yc.algorithm.leetcode;

/**
 * 链表反转
 */
public class ReverseLink {

    // Definition for singly-linked list.
    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
   }

   public static ListNode reverseNode(ListNode head) {
       ListNode prev = null;
       ListNode cur = head;
       while(cur != null) {
           ListNode next = cur.next;
           cur.next = prev;
           prev = cur;
           cur = next;
       }
       return prev;
   }


   // 有序链表合并，合并后还是一个有序链表
   public static ListNode mergeTwoList(ListNode l1, ListNode l2) {
        ListNode preHead = new ListNode(-1);
        ListNode prev = preHead;

        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                prev.next = l1;
                l1 = l1.next;
            } else {
                prev.next = l2;
                l2 = l2.next;
            }
            prev = prev.next;
        }

        // 补充最后节点
        prev.next = l1 == null ? l2 : l1;

        return preHead.next;
   }
}
